<template>
  <div>
    <el-collapse
      v-if="
        Array.isArray(activeitem.childrenList) &&
        activeitem.childrenList.length > 0
      "
    >
      <template v-for="child in activeitem.childrenList">
        <div
          :key="child.id"
          :style="'display: flex;width: 100%;'"
          v-if="child.nodeType == 1"
        >
          <div
            v-for="item in child.level"
            :key="item"
            :style="'width: 10px; height: 20px'"
          ></div>
          <el-collapse-item
            style="width: 100%"
            v-if="child.nodeType == 1"
            :key="child.id"
            :title="child.title"
          >
            <recursive-collapse
              v-if="child.childrenList && child.childrenList.length > 0"
              :activeitem="child"
              :abcShow="abcShow"
              :isWatch="isMuWatch"
            />
          </el-collapse-item>
        </div>
      </template>
      <template v-for="child in activeitem.childrenList">
        <div
          :key="child.id"
          :style="'display: flex;'"
          v-if="child.nodeType == 0"
        >
          <div
            :style="'width: 10px; height: 20px'"
            v-for="item in child.level"
            :key="item"
          ></div>
          <div style="display: flex">
            <div
              v-if="child.nodeType == 0 && child.mp4Url"
              :key="child.id"
              style="width: 20%"
            >
              <div class="vd-box" @click="handleOpenVideo(child)">
                <img
                  :src="child.imgUrl"
                  v-if="child.mp4Url.split('.').pop() == 'mp4'"
                  style="height: 60px"
                  alt=""
                />
                <img
                  src="../assets/images/mp3.png"
                  style="height: 60px"
                  alt=""
                  v-if="child.mp4Url.split('.').pop() == 'mp3'"
                />
                <el-tooltip
                  :content="child.title.replace(/&amp/g, '&').replace(/;/g, '')"
                  placement="top"
                  effect="light"
                  popper-class="item-top-intro"
                >
                  <div
                    style="
                      margin-top: 4px;
                      font-size: 16px;
                      width: 160px;
                      display: flex;
                      justify-content: space-evenly;
                    "
                  >
                    <span class="text" v-html="child.title"></span>
                  </div>
                </el-tooltip>
                <!-- <img v-else src="../assets/images/pdf.png" alt="" /> -->
              </div>
            </div>
            <div v-if="child.nodeType == 0 && child.docUrl" :key="child.id">
              <div class="pdf-box" @click="handleOpenOutUrl(child, true)">
                <!-- :href="child.docUrl" target="_blank" -->
                <a>
                  <!-- <img src="../assets/images/shipin.png" alt="" /> -->
                  <img
                    src="../assets/images/docx.png"
                    style="height: 56px"
                    alt=""
                  />
                  <el-tooltip
                    :content="
                      child.title.replace(/&amp/g, '&').replace(/;/g, '')
                    "
                    placement="top"
                    effect="light"
                    popper-class="item-top-intro"
                  >
                    <div
                      style="
                        margin-top: 4px;
                        font-size: 16px;
                        display: flex;
                        width: 160px;
                        justify-content: space-evenly;
                      "
                    >
                      <span class="text" style="width: 62px">{{
                        child.title
                      }}</span>
                    </div>
                  </el-tooltip>
                </a>
                <!-- <img v-else src="../assets/images/pdf.png" alt="" /> -->
              </div>
            </div>
            <div v-if="child.nodeType == 0 && child.fileUrl" :key="child.id">
              <div class="pdf-box" @click="handleOpenOutUrl(child, true)">
                <!-- :href="child.fileUrl" target="_blank" -->
                <a>
                  <!-- <img src="../assets/images/shipin.png" alt="" /> -->
                  <img
                    v-if="child.fileUrl.split('.').pop() == 'pdf'"
                    src="../assets/images/bigPdf.png"
                    style="height: 56px"
                    alt=""
                  />
                  <img
                    v-if="child.fileUrl.split('.').pop() == 'zip'"
                    src="../assets/images/zip.png"
                    style="height: 56px"
                    alt=""
                  />
                  <img
                    v-if="
                      child.fileUrl.split('.').pop() == 'png' ||
                      child.fileUrl.split('.').pop() == 'jpg' ||
                      child.fileUrl.split('.').pop() == 'jpeg'
                    "
                    :src="child.fileUrl"
                    style="height: 56px"
                    alt=""
                  />
                  <el-tooltip
                    :content="
                      child.title.replace(/&amp/g, '&').replace(/;/g, '')
                    "
                    placement="top"
                    effect="light"
                    popper-class="item-top-intro"
                  >
                    <div
                      style="
                        margin-top: 4px;
                        font-size: 16px;
                        width: 160px;
                        display: flex;
                        justify-content: space-evenly;
                      "
                    >
                      <span
                        class="text"
                        style="width: 62px"
                        v-html="child.title"
                      ></span>
                    </div>
                  </el-tooltip>
                </a>
              </div>
            </div>
          </div>
        </div>
      </template>
    </el-collapse>
    <!-- 视频弹窗 -->
    <el-dialog
      :title="videoTitle"
      :visible.sync="videoDialogVisible"
      custom-class="dialog-box"
    >
      <div class="dialog-video" :class="`videoCen${allocationItem.id}`">
        <video
          :ref="`vueMiniPlayer_mulu${allocationItem.id}`"
          @canplay="getVidDur()"
          style="max-height: 500px; min-width: 500px"
          :id="`video_mulu${allocationItem.id}`"
          :src="mp4Url"
          controls="true"
          autoplay
          preload="auto"
          x5-video-player-type="h5"
          x5-video-player-fullscreen="true"
          controlsList="nodownload"
        ></video>
        <img
          src="../assets/images/mp3.png"
          style="width: 100px; margin: 0px auto; position: absolute"
          alt=""
          v-if="mp4Url.split('.').pop() == 'mp3'"
        />
        <div
          ref="watermarkContainer"
          class="watermark-container"
          v-if="mp4Url.split('.').pop() == 'mp4'"
        >
          <p class="watermark-text">
            {{
              $store.state.userData.mobile != ""
                ? $store.state.userData.mobile
                : $store.state.userData.userName
            }}
          </p>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="toggleFullscreen"
          v-if="mp4Url.split('.').pop() == 'mp4'"
          >全屏播放</el-button
        >
        <el-button @click="handleCloseDialog">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { STATUS_CODE_OK } from "@/config";
import { permissionVerification } from "@/api/homePage.js";
import { statisticBackup, statisticLearnTime } from "@/api/resourcesDetails.js";
export default {
  name: "RecursiveCollapse",
  props: {
    abcShow: {
      type: String,
      default: "",
    },
    activeitem: {
      type: Object,
      default() {
        return {};
      },
    },
    // isWatch: {
    //   type: Boolean,
    //   default() {
    //     return false;
    //   },
    // },
  },
  data() {
    return {
      isFullscreen: false, // 控制是否全屏的标志
      videoTitle: "音视频预览", // 视频名称-弹窗
      videoDialogVisible: false, // 视频弹窗显示隐藏
      mp4Url: "", // 视频地址
      timer: null,
      sendPost: null,
      // classId: "88",
      totalTime: "", // 视频总时长
      watchedTime: "", // 视频观看总时长
      allocationItem: {}, // 视频数据
      isPlay: true,
      isMuWatch: false,
    };
  },
  created() {
    // this.isWatch = JSON.parse(sessionStorage.getItem("isWatch"));
    // console.log(this.isWatch,'组件isWatch');
  },
  watch: {
    videoDialogVisible(val) {
      if (!val) {
        var elevideo = document.getElementById(
          `video_mulu${this.allocationItem.id}`
        );
        this.watchedTime = elevideo.currentTime;
        this.totalTime = elevideo.duration;
        clearTimeout(this.timer);
        clearInterval(this.sendPost);
        this.$refs[`vueMiniPlayer_mulu${this.allocationItem.id}`].pause();
        this.handleStatisticLearnTime();
        if (
          !this.isMuWatch &&
          document.getElementById(`video_mulu${this.allocationItem.id}`)
            .currentTime > 30
        ) {
          // if(document.exitFullscreen()){
          //   document.exitFullscreen();
          // }
          this.$message({
            message: "试看30s结束,请联系管理员添加观看权限！",
            type: "warning",
            duration: 5000,
          });
        }
      }
    },
  },
  methods: {
    // 权限校验
    async hanldePermissionVerification(item, pdf = false) {
      console.log(item, pdf);
      let child = item;
      let isPdf = pdf;
      // pdf是否是pdf coll是否是目录
      let { data } = await permissionVerification({
        allocationId: item.allocationId,
        groupType: item.groupType,
        type: item.type,
      });
      if (data.code == STATUS_CODE_OK) {
        this.isMuWatch = data.data;
        if (!data.data) {
          this.$message({
            message: !pdf
              ? "该资源暂无完整观看权限，视频试看时间为30s!"
              : "暂无权限，请联系管理员!",
            type: "warning",
            duration: 3000,
          });
          return;
        }
        if (pdf) {
          window.open(item.fileUrl);
        }
        this.handleStatisticLearnTime(child, isPdf);
      }
    },

    handleOpenOutUrl(item, isTurn) {
      let child = item;
      let isFlag = isTurn;
      this.hanldePermissionVerification(child, isFlag);
      // if (this.isWatch) {
      //   this.handleStatisticLearnTime(child, isFlag);
      //   window.open(child.fileUrl);
      // } else {
      //   this.$message({
      //     message: "暂无查看权限，请联系管理员！",
      //     type: "warning",
      //     duration: 5000,
      //   });
      // }
    },
    toggleFullscreen() {
      this.isFullscreen = !this.isFullscreen;
      // 使用JavaScript来控制全屏，这里是一个简化的示例，实际应用中可能需要考虑兼容性问题
      if (this.isFullscreen) {
        this.$nextTick(() => {
          document
            .querySelector(`.videoCen${this.allocationItem.id}`)
            .requestFullscreen();
        });
        // document.querySelector(".dialog-video").requestFullscreen();
      }
      // else if (document.exitFullscreen) {
      //   document.exitFullscreen();
      // }
    },
    // 鼠标进入事件
    onMouseEnter(item, index, arr) {
      if (item.fileUrl) {
        arr.forEach((eitem) => {
          if (eitem.id == item.id) {
            item.iconCheckout = true;
            arr.splice(index, 1, item);
          }
        });
      } else {
        arr.forEach((eitem) => {
          if (eitem.id == item.id) {
            item.shipinCheckout = true;
            arr.splice(index, 1, item);
          }
        });
      }
    },
    // 视频播放
    handleOpenVideo(item) {
      console.log(item, "allocationItem");
      this.hanldePermissionVerification(item);
      // this.isWatch = sessionStorage.getItem("isWatch");
      if (this.$route.name == "yrIndex" || this.$route.name == "chIndex") {
        this.$message({
          message: "该视频暂无观看权限，请联系管理员！",
          type: "warning",
          duration: 3000,
        });
        return false;
      }
      this.allocationItem = item;
      if (item.fileUrl != "" || item.mp4Url != "") {
        this.handleStatisticBackup(item);
      }
      this.videoDialogVisible = true;
      this.mp4Url = item.mp4Url;
      this.videoTitle = item.title;
    },
    // 关闭弹窗
    handleCloseDialog() {
      this.$refs[`vueMiniPlayer_mulu${this.allocationItem.id}`].pause();
      this.videoDialogVisible = false;
      clearTimeout(this.timer);
      clearInterval(this.sendPost);
    },
    // pdf和视频更新记录
    async handleStatisticLearnTime(item = {}, isPdf = false) {
      if (isPdf) {
        this.allocationItem = item;
      }
      if (
        this.allocationItem.mp4Url != "" ||
        this.allocationItem.fileUrl != "" ||
        this.allocationItem.docUrl != ""
      ) {
        let totalTime = isPdf ? "0" : this.totalTime.toFixed(0);
        let watchedTime = isPdf ? "0" : this.watchedTime.toFixed(0);
        await statisticLearnTime({
          allocationId: this.allocationItem.allocationId,
          watchedTime: watchedTime,
          totalTime: totalTime,
          // classId: this.classId,
          allocationsId: this.allocationItem.id,
          allocationTitle: this.allocationItem.title,
        });
      }
    },
    // 视频时间检测弹窗
    handleOpenMessageBox() {
      this.$confirm("系统检测到您长时间未操作，是否继续播放！", "", {
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "视频继续播放",
          });
          this.isPlay = true;
          this.$refs[`vueMiniPlayer_mulu${this.allocationItem.id}`].pause();
        })
        .catch(() => {
          this.isPlay = true;
        });
    },
    //获取视频播放时间
    getVidDur(e) {
      console.log(e, "event");
      var elevideo = document.getElementById(
        `video_mulu${this.allocationItem.id}`
      );
      // elevideo.addEventListener("seeked", function () {
      //   console.log("禁止拖拽进度条");
      //   // 设置视频的当前时间为视频的总时间，这样进度条会停留在最后一帧

      //   return false;
      // });
      elevideo.addEventListener("timeupdate", () => {
        // console.log(elevideo.currentTime,this.isWatch);
        this.watchedTime = elevideo.currentTime;
        if (elevideo.currentTime > 30 && !this.isMuWatch) {
          this.handleCloseDialog(); //暂停
          return false;
        }
      });
      elevideo.addEventListener("play", () => {
        this.watchedTime = elevideo.currentTime;
        this.totalTime = elevideo.duration;
        //播放
        console.log("开始播放");
        clearTimeout(this.timer);
        clearInterval(this.sendPost);
        this.timer = setTimeout(() => {
          this.$refs[`vueMiniPlayer_mulu${this.allocationItem.id}`].pause(); //暂停
          this.handleOpenMessageBox();
        }, 3090 * 5 * 60);
        this.sendPost = setInterval(() => {
          this.handleStatisticLearnTime();
        }, 1000 * 1 * 60);
      });
      elevideo.addEventListener("playing", () => {
        this.watchedTime = elevideo.currentTime;
        this.totalTime = elevideo.duration;
        //播放中
        console.log("播放中");
      });
      elevideo.addEventListener("waiting", () => {
        //加载
        console.log("加载中");
      });
      elevideo.addEventListener("pause", () => {
        this.watchedTime = elevideo.currentTime;
        this.totalTime = elevideo.duration;
        //暂停
        clearTimeout(this.timer);
        clearInterval(this.sendPost);
        console.log("暂停");
      });
      elevideo.addEventListener(
        "ended",
        () => {
          this.watchedTime = elevideo.currentTime;
          this.totalTime = elevideo.duration;
          //结束
          console.log("播放结束");
          clearTimeout(this.timer);
          clearInterval(this.sendPost);
        },
        false
      );
    },
    async handleStatisticBackup(item) {
      // 播放速度
      // if (this.$refs.vueMiniPlayer.playbackRate) {
      //   this.$refs.vueMiniPlayer.playbackRate = 1;
      // }
      let { data } = await statisticBackup({
        allocationId: item.allocationId,
        // classId: this.classId,
        allocationsId: item.id,
      });
      if (data.data == null) {
        // this.$refs[`vueMiniPlayer_mulu${this.allocationItem.id}`].pause();
        this.$refs[
          `vueMiniPlayer_mulu${this.allocationItem.id}`
        ].currentTime = 0;
      } else {
        this.$refs[`vueMiniPlayer_mulu${this.allocationItem.id}`].currentTime =
          data.data.watchedTime;
      }
    },
    // 鼠标离开事件
    onMouseLeave(item, icon, index, arr) {
      if (item.fileUrl) {
        arr.forEach((eitem) => {
          if (eitem.id == item.id) {
            item.iconCheckout = false;
            arr.splice(index, 1, item);
          }
        });
      } else {
        arr.forEach((eitem) => {
          if (eitem.id == item.id) {
            item.shipinCheckout = false;
            arr.splice(index, 1, item);
          }
        });
      }
    },
  },
};
</script>
<style scoped lang="scss">
.dialog-box {
  width: 80vw !important; /* 80%的视口宽度 */
  height: 80vh !important; /* 80%的视口高度 */
  max-width: 80% !important; /* 限制最大宽度，以防比例失真 */
  max-height: 80% !important; /* 限制最大高度 */
}
::v-deep .el-dialog {
  margin-top: 2vh !important;
  width: 70% !important;
}
/* 视频元素自适应 */
.dialog-video video {
  width: 100% !important; /* 让视频宽度充满对话框 */
  height: auto !important; /* 自动调整高度以保持宽高比 */
  max-height: calc(
    100% - 40px
  ) !important; /* 减去可能存在的顶部标题和底部按钮的高度 */
  object-fit: contain !important; /* 保持视频内容不失真 */
}
::v-deep .el-dialog__body {
  padding: 0px !important;
}
/* 如果需要调整水印容器的位置或大小，也可以在这里设置 */
.watermark-container {
  position: absolute !important; /* 假设水印需要绝对定位 */
  bottom: 10px !important; /* 距离底部的距离，按需调整 */
  // left: 10px !important; /* 距离左边的距离，按需调整 */
  /* 其他样式 */
}
video::-webkit-media-controls-fullscreen-button {
  display: none !important;
}
.watermark-container {
  position: absolute;
  top: 0;
  left: 10%;
  width: 1200px;
  // width: 100% !important;
  // height: 100% !important;
  // display: flex;
  // justify-content: center;
  // align-items: center;
  pointer-events: none !important; /* 确保水印不会响应鼠标事件 */
  opacity: 0.3;
}

.watermark-text {
  width: 300px;
  color: pink;
  font-size: 3em;
  position: relative;
  animation: ball 60s linear infinite !important; /* 飘动动画 */
}

@keyframes ball {
  0% {
    top: 0px;
    left: 0px;
  }
  25% {
    top: 0px;
    left: 70%;
  }
  50% {
    top: 700px;
    left: 70%;
  }
  75% {
    top: 700px;
    left: 0px;
  }
  100% {
    top: 0px;
    left: 0px;
  }
}
.text {
  font-size: 12px;
  // width: 200px;
  text-align: left;
  word-break: break-all;
}
.text {
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden; //溢出内容隐藏
  text-overflow: ellipsis; //文本溢出部分用省略号表示
  display: -webkit-box; //特别显示模式
  -webkit-line-clamp: 2; //行数
  line-clamp: 2;
  -webkit-box-orient: vertical;
}
::v-deep .el-collapse {
  display: flex;
  flex-wrap: wrap;
}
::v-deep .el-collapse-item__content {
  padding-bottom: 0px;
}
::v-deep .el-collapse-item__header {
  padding-left: 40px !important;
}
::v-deep .el-dialog__title {
  word-break: break-all;
}
.pdf-box {
  // width: 100%;
  width: 170px;
  display: flex;
  align-items: center;
  padding: 18px 40px;
  color: #333;
}
.pdf-box a {
  width: 100%;
  color: #333;
  font-size: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.pdf-box:hover {
  background: #f5f8fa;
  color: #1968fa;
}
.pdf-box:hover a {
  color: #1968fa;
}
.vd-box {
  cursor: pointer;
  color: #333;
  .text {
    font-size: 12px;
    // width: 200px;
    text-align: left;
    word-break: break-all;
  }
  width: 170px;
  // width: 200px;
  padding: 18px 40px;
  display: flex;
  align-items: center;
  flex-direction: column;
  align-items: center;
}
.vd-box:hover {
  background: #f5f8fa;
  color: #1968fa;
}
.dialog-box {
  .dialog-video {
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    // max-height: 700px;
    // max-width: 1200px;
    // overflow: auto;
  }
}
</style>
